define([ 'app/utils/WebUtils', 
		'app/service/GeneralServices', 
		'underscore',
		'app/utils/HttpClientUtils',
		'app/utils/TimerUtils', 
        'app/utils/WebSocketUtils',
		'app/utils/AMUIPaginationUtils',
		'app/utils/AMUICookieUtils', 
		'app/utils/CommonUtils'

], function(WebUtils, gs, _, hc, TimerUtils,WebSocketUtils, AMUIPaginationUtils, AMUICookieUtils

) {

	var rt = [];
	var live_start_t = 0;
	var now_time_stamp = (new Date()).getTime(); //设置时间戳，用户获取sessionid
	var chattimestamp = now_time_stamp;
	
	var opt = AMUICookieUtils.initializePage();
	opt.fullscreen = $.unicodeToHanzi($.getUrlParam("fullscreen"));// yes - no;
	opt.roomuuid = $.unicodeToHanzi($.getUrlParam("roomuuid"));
	opt.ops = $.unicodeToHanzi($.getUrlParam("ops"));
	console.log(opt);
	var param = {
		roomid : opt.roomuuid,
		userid : opt.useruuid
	};
	
	
	function renderMsg(msg,history){
		
		var divs = $("#msglist");
		
		var self = (msg.useruuid == opt.useruuid);
		var el = $('');
		
		if(msg.type == "txt"){
			
			el = $(
	 		'<div id="'+msg.msgid+'" class="am-g" style="margin-bottom: 5px;">'+
				'<div class="am-u-lg-2"> '+
					'<img class="am-circle" src="'+msg.headimgurl+'" width="40" height="40"/>'+
				'</div>'+
				'<div class="am-u-lg-10" style="font-size:14px;">'+
					'<div>'+msg.name+ (self?'<a class="am-badge am-badge-warning">自己</a>':'')+'</div>'+
					'<div class="aui-chat-content">'+msg.content+'</div>'+
					(self?'<div class="aui-chat-status aui-chat-status-refresh"><a style="color:white;" href="javascript:void(0);" id="delBtn_'+msg.msgid+'" data-msgid="'+msg.msgid+'">撤回</a></div>' : '')+
				'</div>'+
			'</div>'
			);
		}else if(msg.type == "img"){
			el = $(
			'<div id="'+msg.msgid+'" class="am-g" style="margin-bottom: 10px;">'+
				'<div class="am-u-lg-2"> '+
					'<img class="am-circle" src="'+msg.headimgurl+'" width="40" height="40"/>'+
				'</div>'+
				'<div class="am-u-lg-10" style="font-size:14px;">'+
					'<div>'+msg.name+ (self?'<a class="am-badge am-badge-warning">自己</a>':'')+'</div>'+
					'<div class="aui-chat-content"><img src="'+msg.newsrc+'" style="width: 100%;"></div>'+
					(self?'<div class="aui-chat-status aui-chat-status-refresh"><a href="javascript:void(0);" id="delBtn_'+msg.msgid+'" data-msgid="'+msg.msgid+'">撤回</a></div>' : '')+
				'</div>'+
			'</div>'
			);
			
		}else if(msg.type == "audio"){
			el = $(
			'<div id="'+msg.msgid+'" class="am-g" style="margin-bottom: 5px;">'+
				'<div class="am-u-lg-2"> '+
					'<img class="am-circle" src="'+msg.headimgurl+'" width="40" height="40"/>'+
				'</div>'+
				'<div class="am-u-lg-10" style="font-size:14px;">'+
					'<div>'+msg.name+ (self?'<a class="am-badge am-badge-warning">自己</a>':'')+'</div>'+
					'<div class="aui-chat-content"><audio controls src="'+msg.newsrc+'" style="width: 100%;"></div>'+
					(self?'<div class="aui-chat-status aui-chat-status-refresh"><a href="javascript:void(0);" id="delBtn_'+msg.msgid+'" data-msgid="'+msg.msgid+'">撤回</a></div>' : '')+
				'</div>'+
			'</div>'
			);
			
		}
		
		
		if(history){
			divs.prepend(el);
		}else{
			divs.append(el);
		}
		
		$("#delBtn_"+msg.msgid).click(function(){
			wssend({
				msgid:$(this).data("msgid"),
				type:"takeback"
			});
		});
	}
	
	function fetchHistory(){
		var url = "wjt/fetchhistory";
		var body = {
			timestamp: chattimestamp,
			roomuuid: opt.roomuuid,
			size: "100"
		};
		
		hc.sendPOST(url,body,renderHistory,null,true);
	}
	

	function renderHistory(resp){
	
		if(resp.result.length == 0){
			//scrollToBottom();
			//return;
			return;
		}
	
		for(var i = 0 ;i < resp.result.length; i++){
		
			chattimestamp = resp.result[i].wmRoomChathistory.time;
//			{"wmRoomChathistory":{"id":1526,"useruuid":"b69a5be1-2b74-4118-a3bf-72ab8b98799a","roomuuid":"27dd8457-2f67-4b81-8121-dd198c823eb8","time":1489487066393,"content":null,"type":"img","newsrc":"/attachment/chatimg/aed4ed97-d62d-4e42-be31-2c751303707a","ppt":null,"sec":null,"msgid":"b69a5be1-2b74-4118-a3bf-72ab8b98799a_1489487065714"},"wmUser":{"id":1,"uuid":"b69a5be1-2b74-4118-a3bf-72ab8b98799a","tel":"","name":"a","wxOpenid":null,"wxNickname":null,"wxSex":null,"wxProvince":null,"wxCity":null,"wxCountry":null,"wxHeadimgurl":"","wxPrivilege":null,"wxUnionid":null,"lastlogin":1487166600000,"uAccessToken":"","uExpiresIn":0,"uRefreshToken":"","uScope":null,"openAccessToken":null,"openExpiresIn":null,"openRefreshToken":null,"openScope":null,"openOpenid":null,"createtime":1480989224000,"dyOpenid":null,"dyAccessToken":null,"dyExpiresIn":null,"dyRefreshToken":null,"dyScope":null,"needUpdate":"1","userType":null,"pwd":"0CC175B9C0F1B6A831C399E269772661","email":"a@a.com"}} at CommonUtils.js : 97
			var _headimgurl = resp.result[i].wmUser.wxHeadimgurl;
			if($.isNullStr(_headimgurl)){
				_headimgurl = null;
			}else{
				_headimgurl = (resp.result[i].wmUser.wxHeadimgurl)
			}
			
			var _newsrc = resp.result[i].wmRoomChathistory.newsrc;
			if($.isNullStr(_newsrc)){
				_newsrc = null;
			}else{
				_newsrc = (resp.result[i].wmRoomChathistory.newsrc); 
			}
			
			var o ={
				type: resp.result[i].wmRoomChathistory.type,
				msgid: resp.result[i].wmRoomChathistory.msgid,
				sec: resp.result[i].wmRoomChathistory.sec,
				content: resp.result[i].wmRoomChathistory.content,
				time: resp.result[i].wmRoomChathistory.time,
				unionid: resp.result[i].wmUser.wxUnionid,
				headimgurl: _headimgurl,
				newsrc: _newsrc,
				name: resp.result[i].wmUser.name,
				useruuid: resp.result[i].wmRoomChathistory.useruuid,
				ppt: resp.result[i].wmRoomChathistory.ppt
			};
			
			console.log("msghistory");
			console.log(o);
			renderMsg(o, true);
		}
	
		
		fetchHistory();
	}
	function fetchAllHistory(){
		fetchHistory();
	}
	function wssend(msg){

		if($.isNull(msg)){
			msg = {};
		}
		
		var pattern = "/appchat/room/"+opt.roomuuid+"/user/"+opt.useruuid;
		WebSocketUtils.send(pattern,msg);
	}
	
	function wsselfsend(){
		var msg = {};
		var pattern = "/appchat/private/self/"+opt.useruuid+"/timestamp/"+now_time_stamp;;
		WebSocketUtils.send(pattern,msg);
	}
	function wsinit(){

		var room_subscribe_pattern = "/ws/room/"+opt.roomuuid;
//		var room_private_subscribe_pattern = "/ws/private/room/"+roomuuid+"/user/"+useruuid;
		var self_subscribe_pattern = "/ws/private/self/"+opt.useruuid+"/timestamp/"+now_time_stamp;
		
		
		console.log(room_subscribe_pattern);
		console.log(self_subscribe_pattern);
		//注册监听pattern
		WebSocketUtils.subscribe(room_subscribe_pattern, function(data_pack){

			var data = JSON.parse(data_pack.body);
			console.log(data);
//			{"unionid":null,"headimgurl":"","name":"a","time":1487144011914,"useruuid":"b69a5be1-2b74-4118-a3bf-72ab8b98799a","type":"ignore","roomuuid":"328e4f63-1eb9-420d-9723-6bb85de52657"} 
			if(data.type == "ignore"){
			
			}else if(data.type == "takeback"){
				
				$("#"+data.msgid).remove();
			}else{
			//获取到websocket数据后，发送recieve_room_msg事件，通过RoomChatBodyFrm.js来接收处理
			//通过RoomMiddleFrm更新在线用户信息
				
				renderMsg(data,false);
				//EventUtils.send(api.winName, 'recieve_room_msg', data);
			}
		});
		//注册监听pattern//连接成功后，服务器会发送此信息
		WebSocketUtils.subscribe(self_subscribe_pattern, function(data_pack){
			var data = JSON.parse(data_pack.body);
			console.log(data);
			//sessionid
			opt.sessionid = data.sessionid;
		});
		
			
		var param = {
			userid: opt.useruuid,
			roomid: opt.roomuuid
		};
		var endpointurl = "/appchat_websocket";
		 
		WebSocketUtils.connect(endpointurl, param,function(){
			
			console.log("connected");
			
			
//			
//			//如果连接成功，发送login type
			wssend({
				type:"login",
				userid:opt.useruuid
			});
//			
//			//获取自己的sessionid
			wsselfsend();
//			
//			//获取历史记录
			fetchAllHistory();
//		
//			//关闭过渡窗体RoomStagingFrm
//			EventUtils.send(api.winName, 'close_staging_frm', {});
			
			
		},function(){
		//如果断开连接，则进行重连
		
		});
		
		
	}
	
	function listenEsc(){
		
		$(document).ready(function () {
			/** Coding Here */
		}).keydown(function (e) {
			if (e.which === 27) {
				if($.isNullStr(opt.fullscreen)){
					
				}else if(opt.fullscreen == "yes"){
					var url = location.href;
					url = url.replace("&fullscreen=yes","");
					location.href=url;
				}
					
				/** 这里编写当ESC按下时的处理逻辑！ */
			}
		});
		
	}
	
	function PPTFetchHandle(resp){
		

		
		/////////////
		wsinit();
		////////////
		
		$("#cover").attr("src",$.handleUrl(resp.result.cover));
		$("#roomname").html(resp.result.name);
		$("#username").html(opt.username);
		var pages = resp.result.pages;

		var $slides = $("#ppt-container").find(".am-slides");
		
		for (var i = 0; i < pages.length; i++) {

			if (pages[i].type == "img") {

				pages[i].pageurl = $.handleUrl(pages[i].pageurl);
				
				var w = $("#ppt-container").width();
				
				var h = w * 9/16;
				var $el = $('<li>' + '<img src="' + pages[i].pageurl
						+ '"  style="height:' + h + 'px;width:' + w
						+ 'px;" />' + '</li>');
				$slides.append($el);
			}
		}

		var param = {};
		param.roomuuid = opt.roomuuid;
		
		
		if(opt.ops == "start"){
			
			gs.getScript(param, function(resp) {
				
				if(!$.isNullStr(resp.result.scripts)){
					rt = JSON.parse(resp.result.scripts);
					var len = rt.length;
					if(len > 1){
						live_start_t = rt[len-1].t;	
					}else{
						live_start_t = 0;
					}
					
				}
				
				TimerUtils.startTimer(100, function() {
					live_start_t = live_start_t + 100;
				});
				
				$('#ppt-container').flexslider({
				  playAfterPaused: 8000,
				  animationLoop: false,
				  slideshow: false,
				  slideshowSpeed: 50000000,
				  startAt: 0,
				  touch: true, 
				  before: function(slider) {
				// 		console.log(slider);
				  },
				  after: function(slider) {
					  
					  var goto = slider.animatingTo;
					  
					  var rt_el = {t:live_start_t,p:goto};
					  rt.push(rt_el);
					  var param = {};
					  param.roomuuid = opt.roomuuid;
					  param.scripts = JSON.stringify(rt);
					  gs.saveScript(param,function(resp){
							wssend({
								type:"goto",
								content: ""+goto
							});
					  });
					  console.log(rt_el);
					  
					  
				  }
				  // 设置其他参数
				});

				
				wssend({
					type:"goto",
					content: "0"
				});
			});
			////////////////////-end
		}else{
			
			$('#ppt-container').flexslider({
				  playAfterPaused: 8000,
				  animationLoop: false,
				  slideshow: false,
				  slideshowSpeed: 50000000,
				  startAt: 0,
				  touch: true, 
				  before: function(slider) {
				// 		console.log(slider);
				  },
				  after: function(slider) {

				  }
				  // 设置其他参数
				});
			
		}
	}
	gs.fetchPPT(param, function(resp) {
		console.log(resp);
		if (resp.status == "200") {
			
			if(opt.fullscreen == "yes"){
				
				$("#loading").modal();
				
				setTimeout(function(){
					listenEsc();
					$(".fullcontainer").css({
						"width":"auto"
					});
					$(".fullhide").hide();
					$(".fullwrap").css({
						"padding":0,
						"width": $(window).width()  + "px",
						"height":$(window).height() + "px",
						"position":"absolute"
					});
					$(".fullel").css({
						"width":$(window).width() +"px",
						"height":$(window).height() + "px",
						"position":"absolute",
						"padding":0,
						"margin":0
					});	
					$('#ppt-container').css({
						"width":$(window).width()+"px",
						"height":$(window).height()+"px",
						position:"absolute",
						left:0,
						top:0
					});
					PPTFetchHandle(resp);
					
					$("#loading").modal('close');
				},3000);
			}else{
				
				PPTFetchHandle(resp);
			}
			
			

		}

	});

	console.log(opt);
	
	
	$("#sendMsgBtn").click(function(){
		var val = $("#sendMsgInput").val();
		$("#sendMsgInput").val("");
		
		wssend({
			type:"txt",
			msgid: opt.useruuid + (new Date()).getTime(),
			content: val,
			userid:opt.useruuid
		});
		
	});

	try{
		var cef_msg = {};
		cef_msg.useruuid = opt.useruuid;
		cef_msg.roomuuid = opt.roomuuid;
		cefObject.call("startvideolive",JSON.stringify(cef_msg));	
	}catch(err){
	}	
	return {
		getUseruuid: function(){
			return opt.useruuid;
		}
	};
});